package com.common.secretkey.rsa;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

public class EncryptPasswordExample {
    public static void main(String[] args) {
        try {
            // 用户输入的密码
            String password = "password123";

            // 加载公钥
            byte[] publicKeyBytes = new byte[2048];  // 从文件或数据库等获取公钥的字节数组
            java.security.PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));

            // 使用公钥进行加密
            byte[] encryptedBytes = encryptWithPublicKey(password, publicKey);

            // 将加密后的结果转换为字符串（可选）
            String encryptedPassword = new String(encryptedBytes, StandardCharsets.UTF_8);

            // 输出加密后的密码
            System.out.println("加密后的密码：" + encryptedPassword);

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 使用公钥加密数据
    private static byte[] encryptWithPublicKey(String data, java.security.PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }
}

